package com.qying.rpc.serialzation;

import com.caucho.hessian.io.HessianSerializerInput;
import com.caucho.hessian.io.HessianSerializerOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

public class HessianSerialization implements  RpcSerialzation{
    @Override
    public <T> byte[] serialize(T obj) throws Exception {

        if (Objects.isNull(obj)) {
            throw new NullPointerException();
        }

        byte[] results = null;
        HessianSerializerOutput hessianSerializerOutput;

        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            hessianSerializerOutput = new HessianSerializerOutput(stream);
            hessianSerializerOutput.writeObject(obj);
            hessianSerializerOutput.flush();
            results = stream.toByteArray();
        } catch (IOException e) {
           throw new SerializationException(e);
        }

        return results;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clz) throws Exception {
        if (Objects.isNull(data)) {
            throw new NullPointerException();
        }

        T result;

        try {
            ByteArrayInputStream stream = new ByteArrayInputStream(data);

            HessianSerializerInput hessianSerializerInput = new HessianSerializerInput(stream);

            result = (T) hessianSerializerInput.readObject(clz);
        } catch (IOException e) {
            throw new SerializationException(e);
        }

        return result;
    }

}
